<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3"
      xmlns:shiro="http://www.w3.org/1999/xhtml">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>友和OA管理系统</title>
    <link th:replace="common/Head :: headCss">
    <link th:href="@{/bootstrap/dataTable/datatables.min.css}" rel="stylesheet">

    <style type="text/css">
        .table > tbody > tr > td {
            text-align: center;
        }

        /* dataTables表头居中 */
        .table > thead:first-child > tr:first-child > th {
            text-align: center;
        }
        .table>caption+thead>tr:first-child>td, .table>caption+thead>tr:first-child>th, .table>colgroup+thead>tr:first-child>td, .table>colgroup+thead>tr:first-child>th, .table>thead:first-child>tr:first-child>td, .table>thead:first-child>tr:first-child>th {
            border-top: 0;
            border-bottom: 0;
        }
        .layui-form .layui-form-item label {
            width: 100px;
        }
    </style>
</head>

<body>
<div id="wrapper">
    <nav th:include="common/Left_Ment :: left"></nav>
    <div id="page-wrapper" class="gray-bg">
        <div th:include="common/Head :: head"></div>
        <div class="wrapper wrapper-content animated fadeInRight"  id="wrapperView">
            <div class="row">
                <div class="col-lg-12">
                    <div class="ibox float-e-margins">
                        <!--<div class="ibox-title">
                            <div class="ibox-tools">
                                <a class="collapse-link">
                                    <i class="fa fa-chevron-up"></i>
                                </a>
                                <a class="dropdown-toggle" data-toggle="dropdown" href="#">
                                    <i class="fa fa-wrench"></i>
                                </a>
                                <ul class="dropdown-menu dropdown-user">
                                    <li><a href="#">Config option 1</a>
                                    </li>
                                    <li><a href="#">Config option 2</a>
                                    </li>
                                </ul>
                                <a class="close-link">
                                    <i class="fa fa-times"></i>
                                </a>
                            </div>
                        </div>-->
                        <div class="ibox-content">
                            <div class="table-responsive" id="div-table-container">
                               <!-- <div class="grid-btn" style="float: left;">
                                    <button id="btnAdd" class="layui-btn layui-btn-normal layui-btn-sm"><i class="layui-icon">&#xe608;</i>新建委托</button>
                                </div>-->
                                <table id="myTable" class="table table-striped table-bordered table-hover dataTables-example" style="width: 100%" >
                                    <thead>
                                    <tr>
                                        <th>
                                            <input type="checkbox" name="cb-check-all">
                                        </th>
                                        <th>标题</th>
                                        <th>申请人</th>
                                        <th>申请环节</th>
                                        <th>开始时间</th>
                                        <th>完成时间</th>
                                    </tr>
                                    </thead>
                                    <tfoot>
                                    </tfoot>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>


        <div class="footer">
            <div>
                <strong>Copyright</strong> 星记云典 Company &copy; 2014-2017
            </div>
        </div>

    </div>
</div>

<div th:include="common/Head :: mainJs"></div>
<div th:include="common/Head :: navMenuJs"></div>
<script th:src="@{/bootstrap/dataTable/datatables.min.js}"></script>

<!-- Page-Level Scripts -->
<script type="text/javascript">

    layui.use(['element', 'form', 'laydate'], function () {
        yuheUtils.bindPersonalSetting();
        var $ = layui.jquery, element = layui.element, form = layui.form, laydate = layui.laydate;

        // 选中左侧菜单
        var $thisA = $('a[href="/activiti/apply"]');
        $thisA.parent().attr("class", "active");
        $thisA.parent().parent().attr("class", "nav nav-second-level collapse in");

        var $wrapper = $('#div-table-container');
        var $table = $('#myTable');

        // datatables 初始化，这个已经整合服务端分页了
        var _table = $table.dataTable($.extend(true,{},CONSTANT.DATA_TABLES.DEFAULT_OPTION, {
            ajax : function(data, callback, settings) { // ajax配置为function,手动调用异步查询
                //封装请求参数
                var param = getQueryCondition(data);
                $.ajax({
                    type: "GET",
                    url: "/activiti/apply/list", // 表格数据接口
                    cache : false,  //禁用缓存
                    data: param,    // 传入已封装的参数
                    dataType: "json",
                    success: function(result) {
                        //异常判断与处理
                        if (result.Status !== 0) {
                            layer.msg('查询失败：' + result.msg, {icon: 2});
                            return;
                        }

                        //封装返回数据，这里仅演示了修改属性名
                        var returnData = {};
                        returnData.draw = data.draw;    //这里直接自行返回了draw计数器,应该由后台返回
                        returnData.recordsTotal = result.total;
                        returnData.recordsFiltered = result.total;//后台不实现过滤功能，每次查询均视作全部结果
                        returnData.data = result.data;

                        //调用DataTables提供的callback方法，代表数据已封装完成并传回DataTables进行渲染
                        //此时的数据需确保正确无误，异常判断应在执行此回调前自行处理完毕
                        callback(returnData);
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        layer.msg('查询失败', {icon: 2});
                    }
                });
            },
            columns: [
                CONSTANT.DATA_TABLES.COLUMN.CHECKBOX,
                {
                    className : "ellipsis", //文字过长时用省略号显示，CSS实现
                    data: "name_",
                    width : "100px"
                   /* render : CONSTANT.DATA_TABLES.RENDER.USER_NAME*/  //会显示省略号的列，需要用title属性实现划过时显示全部文本的效果
                },
                {
                    className : "ellipsis",
                    data: "startUserName",
                   /* render : CONSTANT.DATA_TABLES.RENDER.USER_NAME,*/
                    //固定列宽，但至少留下一个活动列不要固定宽度，让表格自行调整。不要将所有列都指定列宽，否则页面伸缩时所有列都会随之按比例伸缩。
                    //切记设置table样式为table-layout:fixed; 否则列宽不会强制为指定宽度，也不会出现省略号。
                    width : "100px"
                },
                {
                    className : "ellipsis", //文字过长时用省略号显示，CSS实现
                    data : "name",
                    width : "150px"
                },
                {
                    data : "createTime",
                    width : "150px"
                },
                {
                    data : "endTime",
                    width : "150px"
                },
                /*{
                    className : "td-operation",
                    data: null,
                    defaultContent:"",
                    orderable : false,
                    width : "120px"
                }*/
            ],
            "createdRow": function ( row, data, index ) {
                //行渲染回调,在这里可以对该行dom元素进行任何操作
                //给当前行加样式
                if (data.role) {
                    $(row).addClass("info");
                }
                //给当前行某列加样式
                // $('td', row).eq(3).addClass(data.status?"text-success":"text-error");
                //不使用render，改用jquery文档操作呈现单元格
                var $btnEdit = $('<button type="button" row-event="edit" class="btn btn-primary btn-xs btn-outline" style="margin-bottom:0">修改</button>');
                var $btnDel = $('<button type="button" row-event="del" class="btn btn-danger btn-xs btn-outline" style="margin-bottom:0">删除</button>');
                $('td', row).eq(6).append($btnEdit).append($btnDel);

            },
            "drawCallback": function( settings ) {
                //渲染完毕后的回调
                //清空全选状态
                $(":checkbox[name='cb-check-all']",$wrapper).prop('checked', false);
                //默认选中第一行
                $("tbody tr",$table).eq(0).click();
            }
        })).api();  //此处需调用api()方法,否则返回的是JQuery对象而不是DataTables的API对象

        // 新建委托事件
      /*  $('#btnAdd').on('click', function () {
            open();
        });

        // 行按钮事件
        $table.on('click', 'button[row-event="edit"]', function () {
            var item = _table.row($(this).closest('tr')).data();
            open(item);
        }).on('click', 'button[row-event="del"]', function () {
            var item = _table.row($(this).closest('tr')).data();
            $.post('/activiti/remove/delegate/' + item.id, function (r) {
                if (r.Status === 0) {
                    layer.msg('删除成功', {icon: 1});
                    tableReload()
                } else {
                    layer.msg('删除失败：' + r.msg, {icon: 2});
                }
            });
        });

        var idx;
        function open(item) {
            var title = '新建委托';
            if (item) {
                title = '修改委托';
                $('select[name="attorney"]').val(item.attorney);
                $('select[name="processDefinitionId"]').val(item.processDefinitionId);

                form.val("myForm", {id: item.id, startTime: item.startTime, endTime: item.endTime});
            } else {
                $('select[name="attorney"]').val('');
                $('select[name="processDefinitionId"]').val('');
                form.val("myForm", {id: '', startTime: '', endTime: ''});
            }
            form.render('select');

            idx = layer.open({
                type: 1,
                title: title,
                skin: 'layui-layer-molv',
                resize: true,
                fixed: true,
                shadeClose: true,
                shade: 0.1,
                scrollbar: false,
                area: ['525px', '575px'],
                content: $('#addLayer'),
                btn: ['确定', '取消'],
                yes: function (index, layaro) {
                    $('#form-submit').click();
                },
                cancel: function (index, layaro) {
                }
            });
        }*/

        /**
         * 获取查询参数
         */
        function getQueryCondition(data) {
            var param = {};
            //组装排序参数
            /*if (data.order&&data.order.length&&data.order[0]) {
                switch (data.order[0].column) {
                }
                param.orderDir = data.order[0].dir;
            }*/
            //组装查询参数
            param.fullSearch = data.search.value;

            // 组装分页参数
            param.current = (data.start / 10) + 1;    // 计算页码
            param.size = data.length;

            return param;
        }

        // 刷新表格
        function tableReload() {
            _table.ajax.reload(function () {
                _table.columns.adjust().draw();

            },false);
        }

        laydate.render({
            elem: '#startTime',
            type: 'datetime'
        });
        laydate.render({
            elem: '#endTime',
            type: 'datetime'
        });

        // 加载select数据
        $.get('/user/list', function (r) {
            var $attorneySel = $('select[name="attorney"]');
            $.each(r, function (i, item) {
                $attorneySel.append('<option value="' + item.uid + '">' + item.userName + '</option>');
            });

            form.render('select');
        });

        $.get('/activiti/deployed/processes', function (r) {
            console.log(r);
            var $processSel = $('select[name="processDefinitionId"]');
            $.each(r.deployedProcesses, function (i, item) {
                $processSel.append('<option value="' + item.processDefId + '">' + item.name + '</option>');
            });

            form.render('select');
        });

        form.on('select(processSel)', function (obj) {
            var select_text = obj.elem[obj.elem.selectedIndex].text;
            $('input[name="processName"]').val(select_text)
        });

        /**
         * 监听表单提交
         */
        form.on('submit(form-submit)', function (obj) {
            var field = obj.field;
            console.log('field=', field);
            var st = (new Date(field.startTime)).getTime();
            var et = (new Date(field.endTime)).getTime();
            if (et - st <= 0) {
                return layer.msg('开始时间不能大于或等于结束时间', {icon: 2})
            }

            $.ajax({
                type: 'POST',
                url: '/activiti/delegate/save',
                data: field,
                async: false,
                success: function (r) {
                    console.log('save r=', r);
                    if (r.Status === 0) {
                        layer.msg('保存成功', {icon: 1});
                        tableReload();
                        layer.close(idx);
                    } else {
                        layer.msg(r.msg, {icon: 2});
                    }
                }
            });
            return false;
        });

    });


</script>

</body>

</html>
